package Arrays101.Day06;

import java.util.TreeSet;

public class Day06_2 {
    public static void main(String[] args) {
        int i = thirdMax(new int[]{ 2,2,3,1});
        System.out.println(i);
    }

    /**
     * Third Maximum Number
     *
     * Given integer array nums, return the third maximum number in this array.
     * If the third maximum does not exist, return the maximum number.
     *
     * @param nums
     * @return
     */
    public static int thirdMax(int[] nums) {
        TreeSet<Integer> treeSet = new TreeSet<>();
        for (int i = 0; i < nums.length; i++) {
            treeSet.add(nums[i]);
            if (treeSet.size()>3){
                treeSet.remove(treeSet.first());
            }
        }
        return treeSet.size()<3?treeSet.last():treeSet.first();
    }
}
